package com.example.demo.advice;

import com.example.demo.domain.CommonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @Description: controller 拦截
 * @Author: yf.ge
 * @Date: 2020/8/19 10:30
 */
@Slf4j
@RestControllerAdvice
public class AdviceController {

    /**
     * controller 统一错误异常处理
     *
     * @param ex 异常信息
     * @return
     */
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(Exception.class)
    public CommonResult badRequestException(Exception ex) {
        if (ex instanceof BusinessException) {
            // 业务异常
            log.error("*****************  业务异常： {}", ex.getMessage());
            return CommonResult.failed(ErrorConstant.ERROR_FOR_BUSINESS, ex.getMessage());
        } else if (ex instanceof MethodArgumentNotValidException) {
            log.error("***************** 参数错误： {}", ex.getMessage());
            MethodArgumentNotValidException argumentNotValidException = (MethodArgumentNotValidException) ex;
            BindingResult bindingResult = argumentNotValidException.getBindingResult();
            return CommonResult.failed(ErrorConstant.ERROR_FOR_PARAMS, bindingResult.getFieldError().getDefaultMessage());
        }
        log.error("系统异常，异常信息为: {}", ex);
        return CommonResult.failed(ErrorConstant.ERROR_FOR_SYSTEM, "亲，系统好像出错了，正在努力维护中");
    }


}
